﻿using CrmField.Win8App.Common;
using CrmField.Win8App.Data;
using CRMField.Win8App.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.StartScreen;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Item Detail Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234232

namespace CrmField.Win8App
{
    /// <summary>
    /// A page that displays details for a single item within a group while allowing gestures to
    /// flip through other items belonging to the same group.
    /// </summary>
    public sealed partial class ItemDetailPage : CrmField.Win8App.Common.LayoutAwarePage
    {
        public ItemDetailPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            if (!CrmContextManager.IsValid()) this.Frame.Navigate(typeof(GroupedItemsPage));

            // Allow saved page state to override the initial item to display
            if (pageState != null && pageState.ContainsKey("SelectedItem"))
            {
                navigationParameter = pageState["SelectedItem"];
            }

            if (ActivityDataSource.CurrentDataSource == null)
            {
                try 
                {                    
                    ActivityDataSource.LoadFromFileOrService(App.DataSourceName);
                }
                catch (Exception)
                {
                    this.Frame.Navigate(typeof(GroupedItemsPage));
                }
            }

            var item = ActivityDataSource.CurrentDataSource.GetItem((Guid)navigationParameter);

            if (item != null)
            {
                this.DefaultViewModel["Group"] = item.Group;
                this.DefaultViewModel["Items"] = item.Group.Items;
                this.flipView.SelectedItem = item;
            }
            else
            {
                this.Frame.Navigate(typeof(GroupedItemsPage));
            }
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
            var selectedItem = this.flipView.SelectedItem;
            // TODO: Derive a serializable navigation parameter and assign it to pageState["SelectedItem"]
        }

        private void Button_Click_Complete(object sender, RoutedEventArgs e)
        {
            ServiceAppointment serviceAppointment = this.flipView.SelectedItem as ServiceAppointment;
            ActivityDataSource.CurrentDataSource.MarkComplete(serviceAppointment);
        }

        private void Button_Click_Reschedule(object sender, RoutedEventArgs e)
        {
            ServiceAppointment appointment = this.flipView.SelectedItem as ServiceAppointment;
            this.dateTimePicker.Value = appointment.ScheduledStart == null ? DateTime.Now.ToString() : appointment.ScheduledStart.Value.ToString();
            rescheduleDialog.IsOpen = true;
        }
        private void Button_Click_UpdateStartcheduleDate(object sender, RoutedEventArgs e)
        {
            ActivityDataSource.CurrentDataSource.ReSchedule(
                this.flipView.SelectedItem as ServiceAppointment,
                 DateTime.Parse(this.dateTimePicker.Value));
            rescheduleDialog.IsOpen = false;
        }

        private void Button_Click_CancelReschedule(object sender, RoutedEventArgs e)
        {
            rescheduleDialog.IsOpen = false;
        }

        /// <summary>
        /// Invoked when an item within the list is selected.
        /// </summary>
        /// <param name="sender">The GridView (or ListView when the application is Snapped)
        /// displaying the selected item.</param>
        /// <param name="e">Event data that describes how the selection was changed.</param>
        void ItemListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (itemListView.SelectedItem != null)
            {
                // Toggle Pin Button
                ToggleAppBarButton(!SecondaryTile.Exists(((ServiceAppointment)itemListView.SelectedItem).ActivityId.Value.ToString()));
            }
        }

        /// <summary>
        /// Changes the style of the PinToAppBarButton to show Pin or Unpin style
        /// </summary>
        /// <param name="showPinButton"></param>
        private void ToggleAppBarButton(bool showPinButton)
        {
            if (PinToAppBarButton != null)
            {
                PinToAppBarButton.Style = (showPinButton) ? (Application.Current.Resources["PinAppBarButtonStyle"] as Style) : (Application.Current.Resources["UnPinAppBarButtonStyle"] as Style);
            }
        }


        async void pinToAppBar_Click(object sender, RoutedEventArgs e)
        {
            this.BottomAppBar.IsSticky = true;

            var appointment = (ServiceAppointment)itemListView.SelectedItem;
            var tileId = appointment.ActivityId.Value.ToString();

            if (SecondaryTile.Exists(tileId))
            {
                SecondaryTile secondaryTile = new SecondaryTile(tileId);
                bool isUnpinned = await secondaryTile.RequestDeleteForSelectionAsync(GetElementRect((FrameworkElement)sender), Windows.UI.Popups.Placement.Above);

                ToggleAppBarButton(isUnpinned);
            }
            else
            {
                Uri logo = new Uri("ms-appx:///Assets/Logo.png");
                string tileActivationArguments = tileId;

                SecondaryTile secondaryTile = new SecondaryTile(tileId,
                                                                appointment.Subject,
                                                                appointment.TimeAndSubject,
                                                                tileActivationArguments,
                                                                TileOptions.ShowNameOnLogo,
                                                                logo);

                secondaryTile.SmallLogo = new Uri("ms-appx:///Assets/SmallLogo.png");

                bool isPinned = await secondaryTile.RequestCreateForSelectionAsync(GetElementRect((FrameworkElement)sender), Windows.UI.Popups.Placement.Above);

                ToggleAppBarButton(!isPinned);
            }
            this.BottomAppBar.IsSticky = false;
        }

        private Rect GetElementRect(FrameworkElement frameworkElement)
        {
            Windows.UI.Xaml.Media.GeneralTransform buttonTransform = frameworkElement.TransformToVisual(null);
            Windows.Foundation.Point point = buttonTransform.TransformPoint(new Point());
            return new Rect(point, new Size(frameworkElement.ActualWidth, frameworkElement.ActualHeight));
        }

    }
}
